﻿using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;


public class ItemPanelView : MonoBehaviour
    {
        private void Start()
        {
            InitUI();
            //默认将第一条数据生成出来
            GenerateItemCell(CharacterModel.Instance.CharacterDatas.First());
        }

        private void InitUI()
        {
            foreach (var data in CharacterModel.Instance.CharacterDatas)
            {
                var go = Instantiate(PrefabManager.Instance.ItemCharacterBtnCell, transform.Find("CharacterBtnParent"));
                go.GetComponentInChildren<Text>().text=data.Name;
                go.GetComponent<Button>().onClick.AddListener(() =>
                {
                    ClearItemParent();
                    GenerateItemCell(data);
                });
            }
        }
        private void Update()
        {
            if (Input.GetMouseButtonDown(1))
            {
                Instantiate(PrefabManager.Instance.MenuPanel, StartGame.Instance.canvas).AddComponent<MenuPanelView>();
                Destroy(gameObject);
            }
        }
        private void GenerateItemCell(CharacterSqliteData data)
        {
            foreach (var item in CharacterModel.Instance.ItemDatas.Where(itemData => itemData.CharacterId==data.Id))
            {
                var go = Instantiate(PrefabManager.Instance.ItemCell, transform.Find("ItemContainer/ItemParent"));
                go.AddComponent<ItemCell>().itemData=item;
            }
        }

        private void ClearItemParent()
        {
            var itemCellParent = transform.Find("ItemContainer/ItemParent");
            for (int i=0; i <itemCellParent.childCount; i++)
            {
                Destroy(itemCellParent.GetChild(i).gameObject);
            }
        }
    }
